﻿using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.ServiceModel.Channels;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using FastestWays.Messages;
using FastestWays.ViewModel;
using GalaSoft.MvvmLight.Messaging;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Maps.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Practices.ServiceLocation;
using GestureEventArgs = System.Windows.Input.GestureEventArgs;

//TODO: 4. Calculate I am lost and recalculate path

namespace FastestWays.Views
{
    //TODO: make header with instructions
    //TODO: make day/ night shifts to map
    //TODO: display no address was found on search
    public partial class MainPage : PhoneApplicationPage
    {
        public MainPage()
        {
            InitializeComponent();

            // Sample code to localize the ApplicationBar
            //BuildLocalizedApplicationBar();
            this.Loaded += MainPageLoaded;
            _main = ServiceLocator.Current.GetInstance<MainViewModel>();
            _main.PositionChangedOnMain += _main_PositionChangedOnMain;
        }

        void _main_PositionChangedOnMain(MainViewModel sender, EventArgs args)
        {
            if (!Dispatcher.CheckAccess())
            {
                Dispatcher.BeginInvoke(() =>
                {
                    SavePrintScreenToFile();
                    UpdateTileWithScreenshots();
                });
            }
            else
            {
                SavePrintScreenToFile();
                UpdateTileWithScreenshots();
            }

        }

        MainViewModel _main;
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            _main = ServiceLocator.Current.GetInstance<MainViewModel>();
            _main.OnNavigatedTo(e);
            DisplayMessagesAccordingToLocationStatus();

            base.OnNavigatedTo(e);
        }

        private void MainPageLoaded(object sender, RoutedEventArgs e)
        {
            Messenger.Default.Register<NavigateToPageMessage>
            (
                this,
                (action) => ReceiveMessage(action)
            );

        }

        private void DisplayMessagesAccordingToLocationStatus()
        {
            if (!settingsOption.IsEnabled)
            {
                MessageBox.Show(
                    "Location Services are disabled in the Phone's Settings, for this application to work correctly you need to enable Location Services in the Phone's Settings");
            }
            else if (!centerButton.IsEnabled)
            {
                MessageBox.Show(
                    "You have disabled Location Services in this App. For this App to work correctly you will need to enable Location Services in the App's Settings");
            }
        }

        private object ReceiveMessage(NavigateToPageMessage action)
        {
            if (action.PageName == "About")
            {
                NavigationService.Navigate(new Uri("/YourLastAboutDialog;component/AboutPage.xaml", UriKind.Relative));
            }
            else
            {
                var page = string.Format("/Views/{0}.xaml", action.PageName);

                NavigationService.Navigate(
                   new System.Uri(page,
                         System.UriKind.Relative));
            }

            return null;
        }

        private void UpdateTileWithScreenshots()
        {
            ShellTile myTile = ShellTile.ActiveTiles.First();
            if (myTile != null)
            {
                FlipTileData newTileData = new FlipTileData()
                    {
                        BackBackgroundImage = new Uri("isostore:/Shared/ShellContent/tile.jpg"),
                        WideBackBackgroundImage = new Uri("isostore:/Shared/ShellContent/WideTile.jpg"),
                    };

                myTile.Update(newTileData);
            }
        }

        private void SavePrintScreenToFile()
        {
            var bmp = new WriteableBitmap((int)myMap.ActualWidth, (int)myMap.ActualHeight);
            bmp.Render(myMap, null);
            bmp.Invalidate();
            if (bmp.Pixels.Count() > 0)
            {
                WriteBitmapToFile(bmp);
            }

        }

        private static void WriteBitmapToFile(WriteableBitmap bmp)
        {
            using (var isoStore = IsolatedStorageFile.GetUserStoreForApplication())
            using (
                var tileFile = isoStore.OpenFile(@"Shared/ShellContent/tile.jpg", FileMode.Create, FileAccess.ReadWrite)
                )
            using (
                var wideTileFile = isoStore.OpenFile(@"Shared/ShellContent/WideTile.jpg", FileMode.Create, FileAccess.ReadWrite)
                )
            {
                bmp.SaveJpeg(tileFile, 336, 336, 0, 80);
                bmp.SaveJpeg(wideTileFile, 691, 336, 0, 80);
            }
        }

        private void MyMapOnLoaded(object sender, RoutedEventArgs e)
        {
            Microsoft.Phone.Maps.MapsSettings.ApplicationContext.ApplicationId = "4e405b91-2806-462e-baf2-a7db633793ef";
            Microsoft.Phone.Maps.MapsSettings.ApplicationContext.AuthenticationToken = "agJmRWVkP1z9ttIlrg3Y3g";
        }

        private void MyMapOnHold(object sender, MouseEventArgs mouseEventArgs)
        {
            _main.MapMovingByFinger = true;
        }



    }
}